package edu.uoc.tds.pec4.gestion.view;

import java.awt.Font;
import java.awt.Rectangle;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.JButton;

import edu.uoc.tds.pec4.beans.Grupo;
import edu.uoc.tds.pec4.client.PanelMenusUI;
import edu.uoc.tds.pec4.gestion.controller.ControladorGrupos;
import edu.uoc.tds.pec4.i18n.TDSLanguageUtils;

import java.awt.Point;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.SwingConstants;




public class PantallaGrupos extends JFrame implements WindowListener{

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JScrollPane jScrollPane = null;
	private JTable jTable = null;
	private GruposJTableModel model = null;
	private JComboBox jComboBox = null;
	private JTextField jTextField1 = null;
	private JButton jButton1 = null;
	private JLabel jLabel1 = null;
	private JButton jButton2 = null;
	private JButton jButton4 = null;
	private JButton jButton6 = null;

	private int numRegistro=0;
	 
	/**
	 * This is the default constructor
	 */
	public PantallaGrupos() {
		super();
		initialize();
		
		
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(800, 479);
		String locale = PanelMenusUI.getIdioma();
		//System.out.println("locale: "+locale);
		boolean existeFicheroMensajes = TDSLanguageUtils.setDefaultLanguage("i18n/"+locale+"_messages");
        if (!existeFicheroMensajes) {
                JOptionPane.showMessageDialog(null, "ERROR: no se encuentra el fichero 'i18n/message.properties'.\nCorrija el error y vuelva a intentarlo","error.general",0);
                System.exit(-1); //abandonamos la aplicacin se trata de un error grave

        }
		this.setContentPane(getJContentPane());
		
		this.setTitle(TDSLanguageUtils.getMessage("gestion.bordeTitulo.grupos"));
		addWindowListener(this);
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */

	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jLabel1 = new JLabel();
			jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
			jLabel1.setBounds(new Rectangle(163, 13, 500, 22));
			jLabel1.setText(TDSLanguageUtils.getMessage("gestion.listadoGrupos.titulo"));
			jLabel1.setFont(new Font("Arial", Font.BOLD, 18));
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(getJScrollPane(), null);
			jContentPane.add(getJComboBox(), null);
			jContentPane.add(getJTextField1(), null);
			jContentPane.add(getJButton1(), null);
			jContentPane.add(jLabel1, null);
			jContentPane.add(getJButton2(), null);
			jContentPane.add(getJButton4(), null);
			jContentPane.add(getJButton6(), null);
			
	  
		}
		return jContentPane;
	}

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setPreferredSize(new Dimension(800, 419));
			jScrollPane.setBounds(new Rectangle(17, 95, 761, 311));
			jScrollPane.setViewportView(getJTable());
			jScrollPane.setBorder(null);
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jTable	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getJTable() {
		model = new GruposJTableModel();
		if (jTable == null) {
			jTable = new JTable();
			jTable.setAutoCreateColumnsFromModel(true);
			jTable.setModel(model);
			
		}
					
		jTable.getColumnModel().getColumn(0).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col1"));
		jTable.getColumnModel().getColumn(0).setPreferredWidth(160);
		jTable.getColumnModel().getColumn(1).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col2"));
		jTable.getColumnModel().getColumn(1).setPreferredWidth(40);
		jTable.getColumnModel().getColumn(2).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col3"));
		jTable.getColumnModel().getColumn(2).setPreferredWidth(50);
		jTable.getColumnModel().getColumn(3).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col4"));
		jTable.getColumnModel().getColumn(3).setPreferredWidth(80);
		jTable.getColumnModel().getColumn(4).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col5"));
		jTable.getColumnModel().getColumn(4).setPreferredWidth(80);
		jTable.getColumnModel().getColumn(5).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col6"));
		jTable.getColumnModel().getColumn(5).setPreferredWidth(120);
		jTable.getColumnModel().getColumn(6).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col7"));
		jTable.getColumnModel().getColumn(6).setPreferredWidth(120);
		
		// Force the header to resize and repaint itself
		jTable.getTableHeader().resizeAndRepaint();
		recuperarDatos(99,"*");
		
		return jTable;
	}
	private void recuperarDatos(int campo, String filtro)
	{
		
		
		try {
			for(String[] e: ControladorGrupos.getlGrupos(campo, filtro)){
		
				model.usuarios.add(e);

				//System.out.println(e);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * This method initializes jComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getJComboBox() {
		if (jComboBox == null) {
			jComboBox = new JComboBox();
			jComboBox.setBounds(new Rectangle(90, 57, 146, 25));
			jComboBox.setSelectedIndex(-1);
			jComboBox.addItem(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col1"));
			jComboBox.addItem(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col2"));
			jComboBox.addItem(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col4"));
			jComboBox.addItem(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col5"));

			
		}
		return jComboBox;
	}

	/**
	 * This method initializes jTextField1	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getJTextField1() {
		if (jTextField1 == null) {
			jTextField1 = new JTextField();
			jTextField1.setBounds(new Rectangle(239, 60, 316, 20));
		}
		return jTextField1;
	}

	/**
	 * This method initializes jButton1 ESTE ES EL BOTON DE BUSCAR
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {

					reactivarTabla();
				}
			});
			jButton1.setBounds(new Rectangle(567, 58, 96, 22));
			jButton1.setText(TDSLanguageUtils.getMessage("gestion.listadoGrupos.btnBuscar"));
		}
		return jButton1;
	}

	/**
	 * This method initializes jButton2	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton2() {
		if (jButton2 == null) {
			jButton2 = new JButton();
			jButton2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					AltaGrupo miPantalla = new AltaGrupo();
					miPantalla.setVisible(true);
				}
			});
			jButton2.setText(TDSLanguageUtils.getMessage("gestion.listadoGrupos.btnAlta"));
			jButton2.setSize(new Dimension(105, 35));
			jButton2.setMnemonic(KeyEvent.VK_UNDEFINED);
			jButton2.setLocation(new Point(50, 418));
		}
		return jButton2;
	}

	/**
	 * This method initializes jButton4	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton4() {
		if (jButton4 == null) {
			jButton4 = new JButton();
			jButton4.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					Grupo grupito = null;
					numRegistro = jTable.getSelectedRow();
				  if(numRegistro != -1){
						String cadena = (String) jTable.getValueAt(jTable.getSelectedRow(), 0);
						int inicio = cadena.indexOf("-"); 
						String cadenita = cadena.substring(0, inicio);
						numRegistro = Integer.parseInt(cadenita);
					try {
						grupito = ControladorGrupos.getGrupo(numRegistro);
					} catch (RemoteException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					ModificacionGrupo miPantallaMod= new ModificacionGrupo(grupito);
					miPantallaMod.setVisible(true);
				  }
				}
				
			});
			jButton4.setText(TDSLanguageUtils.getMessage("gestion.listadoGrupos.btnModificar"));
			jButton4.setSize(new Dimension(105, 35));
			jButton4.setLocation(new Point(326, 418));
		}
		return jButton4;
	}

	/**
	 * This method initializes jButton6	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton6() {
		if (jButton6 == null) {
			jButton6 = new JButton();
			jButton6.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					jContentPane.setVisible(false);
					cierra();
				}
			});
			jButton6.setText(TDSLanguageUtils.getMessage("gestion.listadoGrupos.btnSalir"));
			jButton6.setSize(new Dimension(105, 35));
			jButton6.setPreferredSize(new Dimension(105, 35));
			jButton6.setLocation(new Point(638, 418));
		}
		return jButton6;
	}
	private void cierra(){
		this.dispose();
	}

    /* PARA PROBAR 
	public static void main(String[] args) {
		
		PantallaGrupos mipantalla = new PantallaGrupos();
		mipantalla.setVisible(true);
		

    }
    */
	
    public class GruposJTableModel extends AbstractTableModel {

    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	List<String[]> usuarios = new ArrayList<String[]>();
    	
    	@Override
    	public int getColumnCount() {
    		// TODO Auto-generated method stub
    		return 7;
    	}

    	@Override
    	public int getRowCount() {
    		// TODO Auto-generated method stub
    		return usuarios.size();
    	}

    	@Override
    	public Object getValueAt(int rowIndex, int columnIndex) {
    		// TODO Auto-generated method stub
    		Object resultado = usuarios.get(rowIndex)[columnIndex];
    		
    		
    		return resultado;
    	}

    }

	@Override
	public void windowActivated(WindowEvent arg0) {
		
		if(jTable == null){
			
		}else{
			jComboBox.setSelectedIndex(0);
			jTextField1.setText("");
			reactivarTabla();
			}
	}

	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosing(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	public void reactivarTabla(){
		String datoBuscar = jTextField1.getText();
		int campoBusqueda = 99;
		
		if(datoBuscar != "")
			campoBusqueda = jComboBox.getSelectedIndex();
		Date fecha = null;
		if(campoBusqueda > 1){   //hay que tratar las fechas
			fecha  = deStringToDate(datoBuscar);
			if(fecha == null){ 
				//jTextField1.setText(getFechaActual());
				campoBusqueda = 99;
				datoBuscar ="*";
			}else
				datoBuscar = ""+fecha;
		}
		//System.out.println("dato:"+datoBuscar+" - "+campoBusqueda);
		model = new GruposJTableModel();
		jTable.setAutoCreateColumnsFromModel(true);
		jTable.setModel(model);
		jTable.getColumnModel().getColumn(0).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col1"));
		jTable.getColumnModel().getColumn(0).setPreferredWidth(160);
		jTable.getColumnModel().getColumn(1).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col2"));
		jTable.getColumnModel().getColumn(1).setPreferredWidth(40);
		jTable.getColumnModel().getColumn(2).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col3"));
		jTable.getColumnModel().getColumn(2).setPreferredWidth(50);
		jTable.getColumnModel().getColumn(3).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col4"));
		jTable.getColumnModel().getColumn(3).setPreferredWidth(80);
		jTable.getColumnModel().getColumn(4).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col5"));
		jTable.getColumnModel().getColumn(4).setPreferredWidth(80);
		jTable.getColumnModel().getColumn(5).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col6"));
		jTable.getColumnModel().getColumn(5).setPreferredWidth(120);
		jTable.getColumnModel().getColumn(6).setHeaderValue(TDSLanguageUtils.getMessage("gestion.listadoGrupos.tabla.col7"));
		jTable.getColumnModel().getColumn(6).setPreferredWidth(120);
		
		jTable.getTableHeader().resizeAndRepaint();

		recuperarDatos(campoBusqueda, datoBuscar);

	}
    public static Date deStringToDate(String fecha) {
        SimpleDateFormat formatoDelTexto = new SimpleDateFormat("dd/MM/yyyy");
        Date fechaEnviar = null;
        try {
            fechaEnviar = formatoDelTexto.parse(fecha);
            return fechaEnviar;
        } catch (ParseException ex) {
			JOptionPane.showMessageDialog(null, ex.getMessage(), TDSLanguageUtils.getMessage("gestion.listadoGrupos.error.fecha"), JOptionPane.ERROR_MESSAGE);
            return null;
        }
    }
    public  String getFechaActual() {
        Date ahora = new Date();
        SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");
        return formateador.format(ahora);
    }
	
}

